import 'dart:math';

import 'package:flame/components.dart';
import 'package:flutter_flame/component/SpriteEntity.dart';
import 'package:flutter_flame/config/AssetsName.dart';

// 僵尸头
class NormalZombieHead extends SpriteEntity {
  Vector2 velocity; // 初始速度
  double gravity; // 重力
  double groundY; // 地面Y值
  Vector2 initPosition; // 位置
  double angularVelocity; // 旋转速度

  NormalZombieHead({
    Vector2? velocity,
    this.gravity = 1000,
    required this.groundY,
    Vector2? initPosition,
    double? angularVelocity,
  })  : velocity = velocity ?? Vector2(Random().nextDouble() * 50 + 30, 0),
        initPosition = initPosition ?? Vector2.zero(),
        angularVelocity = 2,
        super(AssetsName.zombieHead);

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    setSize(40);
    position = initPosition;
    priority = zombiePriority + 1;
  }

  @override
  void update(double dt) {
    super.update(dt);
    velocity.y += gravity * dt;
    position += velocity * dt;
    angle += angularVelocity * dt;
    angularVelocity *= 0.99; // 模拟摩擦力

    if (position.y >= groundY) {
      position.y = groundY;
      if (velocity.y > 0) {
        velocity.y = -velocity.y * 0.5;
        if (velocity.y.abs() < 50) {
          removeFromParent();
        }
      }
    }
  }
}
